package booking.gui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import booking.misc.User;

class Login extends JDialog {

	private final JLabel jlblUsername = new JLabel("Username");
	private final JLabel jlblPassword = new JLabel("Password");

	private final JTextField jtfUsername = new JTextField(15);
	private final JPasswordField jpfPassword = new JPasswordField();

	private final JButton jbtOk = new JButton("Login");
	private final JButton jbtCancel = new JButton("Cancel");

	private final JLabel jlblStatus = new JLabel(" ");

	private User user;

	public Login() {
		this(null, true);
	}

	public Login(final JFrame parent, boolean modal) {
		super(parent, modal);

		JPanel p3 = new JPanel(new GridLayout(2, 1));
		p3.add(jlblUsername);
		p3.add(jlblPassword);

		JPanel p4 = new JPanel(new GridLayout(2, 1));
		p4.add(jtfUsername);
		p4.add(jpfPassword);

		JPanel p1 = new JPanel();
		p1.add(p3);
		p1.add(p4);

		JPanel p2 = new JPanel();
		p2.add(jbtOk);
		p2.add(jbtCancel);

		JPanel p5 = new JPanel(new BorderLayout());
		p5.add(p2, BorderLayout.CENTER);
		p5.add(jlblStatus, BorderLayout.NORTH);
		jlblStatus.setForeground(Color.RED);
		jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);

		setLayout(new BorderLayout());
		add(p1, BorderLayout.CENTER);
		add(p5, BorderLayout.SOUTH);
		pack();
		setLocationRelativeTo(null);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		jbtOk.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				login();

			}
		});

		jbtCancel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				setVisible(false);

				// parent.dispose();

				System.exit(0);
			}
		});
	}

	// Försöker logga in
	private void login() {
		// Läser av username, password och anropar User.login.
		String userName = jtfUsername.getText().trim();
		String password = jpfPassword.getText().trim();
		user = User.getUser(userName, password);

		if (user == null) {
			JOptionPane.showMessageDialog(this, "Felaktig inlogging", "FEL",
					JOptionPane.ERROR_MESSAGE);
			
		} else {
			dispose();
		}
	}

	public User getUser() {
		return user;
	}
}
